import { defineComponent, ref, h, type PropType, onMounted, toRaw, Suspense } from 'vue';
import VueRenderer from '@knxcloud/lowcode-vue-renderer';
import { buildComponents, AssetLoader } from '@knxcloud/lowcode-utils';
import type { Asset } from '@alilc/lowcode-types';
import { uuid } from '../../utils/index';
interface PackageInfo {
    package: string;
    library: any;
    urls: any;
    renderUrls?: any;
}

export const VueRender = defineComponent({
    name: 'VueRender',
    props: {
        packages: {
            type: Array as PropType<PackageInfo[]>,
            required: true
        },
        projectSchema: {
            type: Object as any,
            required: true
        }
    },
    setup(props) {
        const schema = ref(null);
        const components = ref([]);
        const isLoading = ref(true); // 添加一个用于追踪加载状态的ref

        async function loadAndRender() {

            const { packages, projectSchema } = props;
            console.log('vueRender:', VueRender);
            console.log('packages:', toRaw(packages));
            console.log('projectSchema', toRaw(projectSchema));
            if (!packages || !projectSchema) {
                return;
            }

            const componentsMapArray = projectSchema.componentsMap || [];
            const componentsMap: any = {};
            componentsMapArray.forEach((component: any) => {
                componentsMap[component.componentName] = component;
            });

            const libraryMap = {} as Record<string, string>;
            const libraryAsset: Asset[] = [];

            toRaw(packages).forEach(({ package: _package, library, urls, renderUrls }) => {
                libraryMap[_package] = library;
                if (renderUrls) {
                    libraryAsset.push(renderUrls);
                } else if (urls) {
                    libraryAsset.push(urls);
                }
            });

            try {
                console.log('libraryAsset:', libraryAsset);
                // libraryAsset.push('http://localhost:5557/js/vue-renderer.js');
                // await new AssetLoader().load(libraryAsset);
                components.value = await buildComponents(libraryMap, componentsMap);
                schema.value = projectSchema.componentsTree?.[0];
                isLoading.value = false; // 数据加载成功后，设置加载状态为false
            } catch (error) {
                console.error('Error loading or building components:', error);
            }
        }

        onMounted(async () => {
            await loadAndRender();
        });

        return () => (
            h('div', { class: 'lowcode-plugin-sample-preview', id: uuid() }, [
                schema.value && components.value ?
                    h(VueRenderer, {
                        class: 'lowcode-plugin-sample-preview-content',
                        schema: toRaw(schema),
                        components: toRaw(components),
                    }) : h('div', { class: 'lowcode-plugin-sample-preview-loading' }, 'loading...'),

            ])
        );
    }
});